import socket
import re


def do_service(client_socket):
    """处理客户端请求"""
    # 获取客户端请求内容,默认是二进制需要解码
    request = client_socket.recv(1024).decode("gbk")
    """request部分内容
    GET /index.html HTTP/1.1
    Host: 127.0.0.1:7890
    Connection: keep-alive
    """
    # 按行截取字符串
    request_line = request.splitlines()
    # 正则匹配第一行内容取出客户端所需资源
    # 首先匹配GET、POST请求方法 此处[^/表示除/外任意字符]可出现一个或多个
    # [^ ]表示除空格外其他字符匹配到HTTP/1.1之前，并分组取第二组内容
    ret = re.match(r"[^/]+(/[^ ]*)", request_line[0])
    print(ret.group(1))
    if ret:
        file_name = ret.group(1)
        if file_name == "/":
            file_name = "/index.html"

    try:
        file = open("../html" + file_name, "rb")
    except Exception as ret:
        # 相应404
        response = "HTTP/1.1 404 NOT FOUND \r\n"
        response += "\r\n"
        response += "----404----"
        client_socket.send(response.encode("gbk"))
    else:
        html_content = file.read()
        file.close()
        # 封装响应头数据
        response = "HTTP/1.1 200 \r\n"
        response += "\r\n"
        # 写出响应头
        client_socket.send(response.encode("gbk"))
        client_socket.send(html_content)

    # 关闭客户端套接字
    client_socket.close()


def main():
    tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_socket.bind(("", 7890))
    tcp_socket.listen(128)
    while True:
        client_socket, client_addr = tcp_socket.accept()
        do_service(client_socket)


if __name__ == '__main__':
    main()
